package com.earstep.controller
{
	import com.earstep.view.ItemEllipse;
	import com.earstep.view.LoginViewMediator;
	import com.earstep.view.MainViewMediator;
	import com.erastep.mvc.EraStepFrame;
	import com.erastep.mvc.ifc.INotification;
	import com.erastep.mvc.module.vo.ModuleVO;
	import com.erastep.util.CommonConstants;
	import com.erastep.util.LogUtil;
	import com.erastep.util.StringUtil;
	
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.MouseEvent;
	import flash.events.NetStatusEvent;
	import flash.net.NetConnection;
	import flash.net.URLRequest;
	import flash.system.ApplicationDomain;
	import flash.system.LoaderContext;
	import flash.utils.getDefinitionByName;
	
	import mx.containers.Canvas;
	import mx.containers.ViewStack;
	import mx.controls.Alert;
	
	import spark.components.Application;
	import spark.components.HGroup;

	/**
	 * @depart 宁波分公司
	 * @author Jarivs
	 * @date 2011/4/1
	 * */
	public class VictopController extends EraStepFrame
	{
		public function VictopController()
		{
			super();
		}

		//module list

		public var mainView:Application;
		
		private var mediator:MainViewMediator;
		
        public var locked:Boolean = false;
		
		private var tempData:Object;
		
		public var company:String;
		
		private var defaultHome:ModuleVO;
		
		public var preLoadHome:Array;
		
		// this is the connection to rtmfp server
		private var netConnection:NetConnection;	
		
		private var SERVER:String = "rtmfp://p2p.rtmfp.net/";
		
		private var developKey:String = "cfc4939d81c4e389b0c39033-3971a0e6d11d";
		
		//private var jsm:JSCourseCommunicatorMediator;
		
		public function init(mgr:Application):void
		{
			mainView = mgr;
			//register main view
			mediator = new MainViewMediator(mgr);
			registerMediator(mediator);
		}
		
		/**
		 * 所有的插件装载成功
		 * */
		public function respondToGetPluginSuccess(note:INotification):void{
			//开始连接到 cirrus 服务器端
			netConnection = new NetConnection();
			netConnection.addEventListener(NetStatusEvent.NET_STATUS,connectHandler);
			netConnection.connect(SERVER+developKey);
			//结束连接
			
			//设置登录信息
			this.userInfo = note.getBody();
			this.userInfo.companyName = company;
			/**
			 * 开始启动心跳
			 * */
			retriveMediator(MainViewMediator.NAME).callFunction("startKeepLive1",null);
			
			var homeList:Array = new Array();
			tempData = note.getBody();
			//获取插件信息
			//sendNotification(MessageConstants.LOAD_PLUGIN_LIST);
			//开始封装数据.
		    LogUtil.print("+++++++++++  开始封装插件数据对象  V1.1++++++++++++!");	
			//开始实例化存储对象
			if(!pluginList){
				pluginList = new Array();
			}
			//LogUtil.print("初始插件数据:"+note.getBody().toString());
			if(note.getBody()){
				var objData:Object = StringUtil.JsonDecode(note.getBody().flexInitData.toString());
				if(objData){
				    var temp:Array = objData.datasets as Array;
					var flg:Boolean,homeTempList:Array,btn:ItemEllipse;
					for each(var item:Object in temp){
						if(item.key == "-100101"){
							homeTempList = item.datas as Array;
							break;
						}
					}
					for each(item in temp){
						if(item.key == "-100201"){
							var property:String;
							var mvo:ModuleVO;
							var arrp:Array;
							if(temp.length > 0){
								arrp = StringUtil.getProperties(item.datas[0]);
							}
							for each(var obj1:Object in item.datas){
								mvo = new ModuleVO();
								for each(property in arrp){
									mvo[property] = obj1[property]
								}
								flg = false;
								for each(var homeItem:Object in homeTempList){
									if(homeItem.resourceid == mvo.resourceid){
										homeList.push(mvo);
										btn = new ItemEllipse();
										btn.cur.visible = false;
										if(preLoadHome.hasOwnProperty(mvo.resourceid)){
											registerModule(mvo.resourceid,preLoadHome[mvo.resourceid].cls);
										}
										if(homeItem.isdefault == 1){
											btn.cur.visible = true;
											this.defaultHome = mvo;
										}
										btn.name = mvo.resourceid;
										btn.addEventListener(MouseEvent.CLICK,showOtherHomePage);
										(mainView["homelistico"] as HGroup).addElement(btn);
										flg = true;
										break;
									}
								}
								if(!flg){
									pluginList[mvo.systemid+"#"+mvo.formid] = mvo;
									pluginList.push(mvo);
								}
								LogUtil.print(mvo.systemid+"#"+mvo.formid);
							}
						}
					}
				}
			}
			
			/*var module:ModuleVO = new ModuleVO();
			module.resourceid = "GX001";
			module.formid = 7002;
			module.systemid = 700;
			module.url = "assets/modules/GX001.swf";
			pluginList[module.systemid+"#"+module.formid] = module;
			pluginList.push(module);*/
			/*var btn:Button;
            for each(var item:Object in homeList){
				mvo = new ModuleVO();
				mvo.resourceid = item.resourceid;
				mvo.formid = item.formid;
				mvo.systemid = item.systemid;
				mvo.url = item.url;
				pluginList[mvo.systemid+"#"+mvo.formid] = mvo;
				pluginList.push(mvo);
				if(item.defaultLoad){
					this.defaultHome = mvo;
				}
				btn = new Button();
				btn.label = mvo.resourceid;
				btn.name = mvo.resourceid;
				(mainView["homelistico"] as HGroup).addElement(btn);
			}	
			*/
			this.userInfo.homelist = homeList;
			if(defaultHome){
				loadHomePage(defaultHome);
			}else{
				retriveMediator(LoginViewMediator.NAME).callFunction("stopEffect");
				LogUtil.print("系统未设置默认门户,开始展示业务门户!")
				var m:ModuleVO = new ModuleVO();
				m.resourceid = CommonConstants.HOMEPAGE;
				m.url = "assets/modules/home/homepage.swf";
				m.name = "业务门户";
				loadHomePage(m);
			}
		}
		
		/**
		 * 连接测试
		 * */
		private function connectHandler(e:NetStatusEvent):void{
			switch(e.info.code)
			{
				case "NetConnection.Connect.Success": //与Stratus链接成功，开始创建/进入组
					LogUtil.print("P2P Server 连接成功!");
					break;
			}
		}
		
		/**
		 * 开始销毁某个插件
		 * */
		public function respondToDestroyPlugin(note:INotification):void{
			trace("开始执行销毁插件操作:"+note.getBody().toString());		
			destroyPlugin(note.getBody().toString());
		}	
		/**
		 *  开始切换到其他门户
		 * */
		private function showOtherHomePage(e:MouseEvent):void
		{
			var hg:HGroup = (mainView["homelistico"] as HGroup);
			var item:ItemEllipse;
			for(var i:uint = 0;i < hg.numElements;i++){
				item = (hg.getElementAt(i) as ItemEllipse);
				if(item == e.currentTarget){
					item.cur.visible = true;
				}else{
					item.cur.visible = false;
				}			
			}
			for each(var item1:Object in this.userInfo.homelist){
				if(item1.resourceid == e.currentTarget.name){
					loadHomePage(item1 as ModuleVO);
				}
			}
		}
		
		private function loadHomePage(m:ModuleVO):void{
			mainView["homelabel"].text = m.name;
			if(!hasLoadedModule(m.resourceid)){
				var loader:Loader = new Loader();
				var context:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain);
				loader.name = m.resourceid;
				loader.contentLoaderInfo.addEventListener(Event.COMPLETE,loadFrameComplete);
				loader.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR,function(e:IOErrorEvent):void{
					LogUtil.print("门户swf源文件加载失败,尝试直接实例!");
					var loader:Loader = e.currentTarget.loader as Loader;
					sendNotification(loader.name,{data:tempData},null,CommonConstants.MODULE)
					mainView.mouseChildren = true;
					mainView.mouseEnabled = true;
				});
				loader.load(new URLRequest(m.url),context);
			}else{
				//直接切换门户
				var mv:ViewStack = mainView["mainView"] as ViewStack;
				var hg:Canvas;
				var flg:Boolean = false;
				for(var i:uint = 0;i < mv.numChildren;i++){
					hg = mv.getChildAt(i) as Canvas;
					if(hg){
						//trace(hg.name);
						if(hg.name == m.resourceid+"_0"){
							mv.selectedChild = hg;
							flg = true;
							break;
						}
					}
				}
				if(!flg){
					sendNotification(m.resourceid,{data:tempData},null,CommonConstants.MODULE)
					mainView.mouseChildren = true;
					mainView.mouseEnabled = true;
				}
			}
		}
		
		/**
		 * 默认门户加载完成
		 * */
		private function loadFrameComplete(e:Event):void{
			LogUtil.print("门户数据加载成功!");
			var loader:Loader = e.currentTarget.loader as Loader;
			var cls:Class = getDefinitionByName("com.victop."+loader.name+".Main") as Class;
			// at here register module
			registerModule(loader.name,cls);
			sendNotification(StringUtil.trim(loader.name),{data:tempData},null,CommonConstants.MODULE)
			mainView.mouseChildren = true;
			mainView.mouseEnabled = true;
			//temp method
			//sendNotification("loginHomePage",,null,defaultHome.resourceid);
		}
		
		public function respondToLoadPluginFail(note:INotification):void{
			Alert.show("加载所有插件数据失败!");
		}
		
	}
}